import { ClientOptions, fetch } from "@tauri-apps/plugin-http";

export interface KoiApiType {
  send<T>(
    url: string,
    method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH",
    data?: T | Record<string, any>,
    config?: RequestInit & ClientOptions
  ): Promise<T>;
  GET<T>(url: string, data?: T | Record<string, any>): Promise<T>;
  POST<T>(url: string, data?: T | Record<string, any>): Promise<T>;
  PUT<T>(url: string, data?: T | Record<string, any>): Promise<T>;
  DELETE<T>(url: string, data?: T | Record<string, any>): Promise<T>;
  PATCH<T>(url: string, data?: T | Record<string, any>): Promise<T>;
}

class KoiApi {
  constructor() {}
  private async buildHttp(url: string, options: RequestInit & ClientOptions) {
    // 构建请求头
    const httpHeaders = new Headers(options.headers || {});
    if (!httpHeaders.get("Content-Type")) {
      httpHeaders.set("Content-Type", "application/json;charset=utf-8");
    }
    httpHeaders.set("Authorization", `Bearer demo`);
    options.headers = httpHeaders;
    try {
      const res = await fetch("http://localhost:8080" + url, options);
      if (!res.ok) {
        throw new Error(`HTTP error! status: ${res.status}`);
      }
      return res;
    } catch (err) {
      console.error("HTTP request failed: ", err);
      throw err; // 继续抛出错误以便调用方处理
    }
  }

  async send<T>(
    url: string,
    method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH",
    data?: T | Record<string, any>,
    config?: RequestInit & ClientOptions
  ): Promise<T> {
    const fetchOptions: RequestInit & ClientOptions = config || {};
    fetchOptions.method = method;
    // 判断是否需要添加请求体
    if (method !== "GET") {
      if (!(data instanceof FormData || data instanceof URLSearchParams)) {
        fetchOptions.body = JSON.stringify(data);
      } else {
        fetchOptions.body = data; // 如果是 FormData 或 URLSearchParams 直接使用
      }
    } else {
      if (data instanceof URLSearchParams) {
        const queryString = new URLSearchParams(data).toString();
        url += `?${queryString}`;
      }
    }

    try {
      const response = await this.buildHttp(url, fetchOptions);

      //检查发送请求是否成功
      if (response.status !== 200) {
        let message = "";
        switch (response.status) {
          case 400:
            message = "错误请求";
            break;
          case 401:
            message = "未授权，请重新登录";
            break;
          case 405:
            message = "请求方法未允许";
            break;
          case 500:
            message = "服务器端出错";
            break;
          default:
            message = "连接错误";
        }
        return Promise.reject(`err: ${message}, status: ${response.status}`);
      }
      return Promise.resolve(await response.json());
    } catch (err) {
      return Promise.reject(`http error: ${err}`);
    }
  }

  async Get<T>(
    url: string,
    data?: T | Record<string, any>,
    config?: RequestInit & ClientOptions
  ): Promise<T> {
    return await this.send(url, "GET", data, config);
  }

  async Post<T>(
    url: string,
    data?: T | Record<string, any>,
    config?: RequestInit & ClientOptions
  ): Promise<T> {
    return await this.send(url, "POST", data, config);
  }

  async Delete<T>(
    url: string,
    data?: T | Record<string, any>,
    config?: RequestInit & ClientOptions
  ): Promise<T> {
    return await this.send(url, "DELETE", data, config);
  }

  async Patch<T>(
    url: string,
    data?: T | Record<string, any>,
    config?: RequestInit & ClientOptions
  ): Promise<T> {
    return await this.send(url, "PATCH", data, config);
  }

  async Put<T>(
    url: string,
    data?: T | Record<string, any>,
    config?: RequestInit & ClientOptions
  ): Promise<T> {
    return await this.send(url, "PUT", data, config);
  }
}

export default () => {
  return new KoiApi();
};
